package com.baizhi.controller;

import com.baizhi.constants.RedisPrefix;
import com.baizhi.dto.LoginDTO;
import com.baizhi.dto.UpdateUserDTO;
import com.baizhi.entity.User;
import com.baizhi.feign.SmsFeign;
import com.baizhi.po.OneUserPO;
import com.baizhi.po.PlayedPO;
import com.baizhi.po.QueryByIdUserPO;
import com.baizhi.po.UserPO;
import com.baizhi.service.PlayedService;
import com.baizhi.service.UserService;
import com.baizhi.util.TokenUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@RefreshScope
@RestController
@RequestMapping
public class UsersController {

    private static final Logger log = LoggerFactory.getLogger(UsersController.class);
    private final UserService userService;
    private final SmsFeign smsFeign;
    private final RedisTemplate redisTemplate;
    private final RabbitTemplate rabbitTemplate;
    @Autowired
    private PlayedService playedService;

    @Autowired
    public UsersController(UserService userService, SmsFeign smsFeign, RedisTemplate redisTemplate, RabbitTemplate rabbitTemplate) {
        this.userService = userService;
        this.smsFeign = smsFeign;
        this.redisTemplate = redisTemplate;
        this.rabbitTemplate = rabbitTemplate;
    }

    /**
     * 登录
     */
    @PostMapping("tokens")
    public Map<String, String> login(@RequestBody LoginDTO loginDTO) {
        System.out.println("loginDTO = " + loginDTO);
        String token = null;
        String captcha = loginDTO.getCaptcha();
        User user = null;
        Object code = null;
        String anObject = "-1";

        //生产者发送消息
        rabbitTemplate.convertAndSend("login", loginDTO.getPhone());
        //从redis中取出验证码进行验证

        code = redisTemplate.opsForValue().get(RedisPrefix.MSG_PREFIX + loginDTO.getPhone());

//        boolean equals = StringUtils.equals(code, loginDTO.getCaptcha());
        //根据验证码进行判断
        if (code != null) {
            anObject = code.toString();
        }

        System.out.println("captcha = " + captcha);
        System.out.println("anObject = " + anObject);
        if (captcha.equals(anObject)) {
            /**
             * 正确，发布生产者消息,
             *  一个去数据库中获取数据
             *  一个去进行生成令牌
             *  最后将数据作为值，令牌作为键进行redis存储为map
             *  返回数据token,集合map
             */
            //获取用户信息
            user = userService.login(loginDTO.getPhone());
            //根据用户id生成token信息
            Integer id = user.getId();
            Long uid = id.longValue();
            token = TokenUtils.sign(uid);
            String newToken = RedisPrefix.USER_TOKEN_PREFIX + token;
            //设置超时时间为七天
            redisTemplate.opsForValue().set(newToken, user, 7, TimeUnit.DAYS);
        } else {
            //不正确
            throw new RuntimeException("您输入的验证码无效");
        }
        Map<String, String> map = new HashMap<>();
        map.put("token", token);
        return map;
    }

    /**
     * 退出
     */
    @DeleteMapping("token")
    public void exit(@RequestParam String token) {
        Boolean delete = redisTemplate.delete(RedisPrefix.USER_TOKEN_PREFIX + token);
        System.out.println("delete = " + delete);
    }

    /**
     * 已登录用户信息
     */
    @GetMapping("user")
    public UserPO queryByPhone(@RequestParam("token") String token) {
        /**
         * 根据token,拼接前缀去redis中获取对应的数据
         */
        Object o = redisTemplate.opsForValue().get(RedisPrefix.USER_TOKEN_PREFIX + token);
        System.out.println("o = " + o);
        UserPO userPO = new UserPO();
        BeanUtils.copyProperties(o, userPO);
        return userPO;
    }


    @GetMapping("user/{user_id}")
    public QueryByIdUserPO queryById(@PathVariable("user_id") Integer id) {
        log.info("用户id {}", id);
        QueryByIdUserPO queryByIdUserPO = userService.queryById(id);
        return queryByIdUserPO;
    }

    /**
     *
     */
    @PatchMapping("user")
    public UserPO updateUser(@RequestParam("token") String token, @RequestBody UpdateUserDTO updateUserDTO) {
        User user = (User) redisTemplate.opsForValue().get(RedisPrefix.USER_TOKEN_PREFIX + token);
        Integer id = user.getId();
        UserPO userPO = userService.updateUser(id, updateUserDTO);
        return userPO;
    }

    @GetMapping("user/queryByUid/{uid}")
    public String queryByUid(@PathVariable("uid") Integer uid) {
        String s = userService.queryByUid(uid);
        return s;
    }

    @GetMapping("user/queryById/{id}")
    public OneUserPO queryOneById(@PathVariable("id") Integer id) {
        OneUserPO oneUserPO = userService.queryOneById(id);
        return oneUserPO;
    }

    @GetMapping("/user/played")
    public List<PlayedPO> played(@RequestParam("token") String token,
                                 @RequestParam(name = "page", required = false, defaultValue = "1") Integer page,
                                 @RequestParam(name = "per_page", required = false, defaultValue = "1") Integer per_page) {
        //根据token，获取当前登录用户
        User user = (User) redisTemplate.opsForValue().get(RedisPrefix.USER_TOKEN_PREFIX + token);
        Integer userId = user.getId();
        //查看播放历史表
        List<PlayedPO> list = playedService.quweyAllVideo(userId, page, per_page);
        return list;
    }
    

}
